# -*- coding: utf-8 -*-
"""
收货地址控制层

负责处理收货地址相关的HTTP请求和响应
"""
from fastapi import APIRouter, HTTPException, Depends
from fastapi.security import HTTPBearer, HTTPAuthorizationCredentials
from pydantic import BaseModel, Field
from typing import Optional
from app.services.address_service import AddressService
from app.services.user_service import UserService

router = APIRouter(
    prefix="/address",
    tags=["address"],
    responses={404: {"description": "Not found"}}
)

# HTTP Bearer token scheme
security = HTTPBearer()

# 初始化服务层
address_service = AddressService()
user_service = UserService()

# Pydantic 模型
class AddressCreateRequest(BaseModel):
    name: str = Field(..., description="收货人姓名")
    phone: str = Field(..., description="手机号码")
    gender: Optional[str] = Field("male", description="性别: male/female")
    type: Optional[str] = Field("home", description="地址类型: home/office/other")
    province: str = Field(..., description="省份")
    city: str = Field(..., description="城市")
    district: str = Field(..., description="区/县")
    detail: str = Field(..., description="详细地址")
    isDefault: Optional[bool] = Field(False, description="是否默认地址")


class AddressUpdateRequest(BaseModel):
    name: Optional[str] = Field(None, description="收货人姓名")
    phone: Optional[str] = Field(None, description="手机号码")
    gender: Optional[str] = Field(None, description="性别: male/female")
    type: Optional[str] = Field(None, description="地址类型: home/office/other")
    province: Optional[str] = Field(None, description="省份")
    city: Optional[str] = Field(None, description="城市")
    district: Optional[str] = Field(None, description="区/县")
    detail: Optional[str] = Field(None, description="详细地址")
    isDefault: Optional[bool] = Field(None, description="是否默认地址")


# 依赖注入：获取当前用户
async def get_current_user(credentials: HTTPAuthorizationCredentials = Depends(security)):
    """获取当前登录用户（依赖注入用）"""
    access_token = credentials.credentials
    user = user_service.verify_token(access_token)
    
    if not user:
        raise HTTPException(status_code=401, detail="请先登录")
    
    return user


@router.post("/create")
async def create_address(
    request: AddressCreateRequest,
    current_user: dict = Depends(get_current_user)
):
    """创建收货地址"""
    try:
        user_id = str(current_user.get('user_id'))
        
        address_data = {
            "name": request.name,
            "phone": request.phone,
            "gender": request.gender,
            "type": request.type,
            "province": request.province,
            "city": request.city,
            "district": request.district,
            "detail": request.detail,
            "is_default": request.isDefault
        }
        
        address = address_service.create_address(user_id, address_data)
        
        return {
            "code": 200,
            "message": "地址创建成功",
            "data": address
        }
        
    except ValueError as e:
        raise HTTPException(status_code=400, detail=str(e))
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"创建地址失败: {str(e)}")


@router.put("/update/{address_id}")
async def update_address(
    address_id: str,
    request: AddressUpdateRequest,
    current_user: dict = Depends(get_current_user)
):
    """更新收货地址"""
    try:
        user_id = str(current_user.get('user_id'))
        
        # 只包含非空字段
        address_data = {}
        if request.name is not None:
            address_data["name"] = request.name
        if request.phone is not None:
            address_data["phone"] = request.phone
        if request.gender is not None:
            address_data["gender"] = request.gender
        if request.type is not None:
            address_data["type"] = request.type
        if request.province is not None:
            address_data["province"] = request.province
        if request.city is not None:
            address_data["city"] = request.city
        if request.district is not None:
            address_data["district"] = request.district
        if request.detail is not None:
            address_data["detail"] = request.detail
        if request.isDefault is not None:
            address_data["is_default"] = request.isDefault
        
        success = address_service.update_address(address_id, user_id, address_data)
        
        return {
            "code": 200,
            "message": "地址更新成功",
            "data": {"updated": success}
        }
        
    except ValueError as e:
        raise HTTPException(status_code=400, detail=str(e))
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"更新地址失败: {str(e)}")


@router.delete("/delete/{address_id}")
async def delete_address(
    address_id: str,
    current_user: dict = Depends(get_current_user)
):
    """删除收货地址"""
    try:
        user_id = str(current_user.get('user_id'))
        
        success = address_service.delete_address(address_id, user_id)
        
        return {
            "code": 200,
            "message": "地址删除成功",
            "data": {"deleted": success}
        }
        
    except ValueError as e:
        raise HTTPException(status_code=400, detail=str(e))
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"删除地址失败: {str(e)}")


@router.get("/list")
async def get_address_list(current_user: dict = Depends(get_current_user)):
    """获取用户地址列表"""
    try:
        user_id = str(current_user.get('user_id'))
        
        addresses = address_service.get_user_addresses(user_id)
        
        return {
            "code": 200,
            "message": "获取地址列表成功",
            "data": {
                "addresses": addresses,
                "total": len(addresses)
            }
        }
        
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"获取地址列表失败: {str(e)}")


@router.get("/detail/{address_id}")
async def get_address_detail(
    address_id: str,
    current_user: dict = Depends(get_current_user)
):
    """获取地址详情"""
    try:
        user_id = str(current_user.get('user_id'))
        
        address = address_service.get_address_detail(address_id, user_id)
        
        if not address:
            raise HTTPException(status_code=404, detail="地址不存在")
        
        return {
            "code": 200,
            "message": "获取地址详情成功",
            "data": address
        }
        
    except HTTPException:
        raise
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"获取地址详情失败: {str(e)}")


@router.put("/set-default/{address_id}")
async def set_default_address(
    address_id: str,
    current_user: dict = Depends(get_current_user)
):
    """设置默认地址"""
    try:
        user_id = str(current_user.get('user_id'))
        
        success = address_service.set_default_address(address_id, user_id)
        
        return {
            "code": 200,
            "message": "设置默认地址成功",
            "data": {"updated": success}
        }
        
    except ValueError as e:
        raise HTTPException(status_code=400, detail=str(e))
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"设置默认地址失败: {str(e)}")


@router.get("/default")
async def get_default_address(current_user: dict = Depends(get_current_user)):
    """获取默认地址"""
    try:
        user_id = str(current_user.get('user_id'))
        
        address = address_service.get_default_address(user_id)
        
        if not address:
            return {
                "code": 200,
                "message": "暂无默认地址",
                "data": None
            }
        
        return {
            "code": 200,
            "message": "获取默认地址成功",
            "data": address
        }
        
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"获取默认地址失败: {str(e)}")


@router.get("/detail/{address_id}")
async def get_address_detail(
    address_id: str,
    current_user: dict = Depends(get_current_user)
):
    """获取地址详情"""
    try:
        user_id = str(current_user.get('user_id'))
        
        address = address_service.get_address_detail(address_id, user_id)
        
        if not address:
            raise HTTPException(status_code=404, detail="地址不存在")
        
        return {
            "code": 200,
            "message": "获取地址详情成功",
            "data": address
        }
        
    except HTTPException:
        raise
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"获取地址详情失败: {str(e)}")

@router.get("/statistics")
async def get_address_statistics(current_user: dict = Depends(get_current_user)):
    """获取地址统计信息"""
    try:
        user_id = str(current_user.get('user_id'))
        
        stats = address_service.get_address_statistics(user_id)
        
        return {
            "code": 200,
            "message": "获取地址统计成功",
            "data": stats
        }
        
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"获取地址统计失败: {str(e)}") 